package com.jd.risk.bankorder.service.bankorder;

import com.alibaba.fastjson.JSON;
import com.jd.risk.bankorder.common.CommonResult;
import com.jd.risk.bankorder.dao.bankorder.TeslaBankRequestMapper;
import com.jd.risk.bankorder.entity.bankorder.TeslaBankRequest;
import com.jd.risk.bankorder.entity.bankorder.TeslaBankRequestExample;
import com.jd.risk.bankorder.entity.bankorder.TeslaOrderInfo;
import com.jd.risk.bankorder.entity.privilege.User;
import com.jd.risk.bankorder.util.CodeInfoUtils;
import com.jd.risk.bankorder.util.CommonUtil;
import com.jd.risk.bankorder.util.excel.FileExcelUtil;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateFormatUtils;
import org.apache.commons.lang.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.*;
import java.math.BigDecimal;
import java.text.ParseException;
import java.util.*;

/**
 * Created by songjunou on 2017/5/17.
 */
@Service
public class BankOrderService {


    @Autowired
    private TeslaBankRequestMapper teslaBankRequestMapper;

    public CommonResult<String> saveRequest(TeslaBankRequest teslaBankRequest) {
        User user = CommonUtil.getCurrentUser();
        CommonResult<String> result = new CommonResult<String>();
        TeslaBankRequestExample teslaBankRequestQuery = new TeslaBankRequestExample();
        teslaBankRequestQuery.createCriteria().andBankRequestNoEqualTo(teslaBankRequest.getBankRequestNo());
         Long count = teslaBankRequestMapper.countByExample(teslaBankRequestQuery);
         if(count >0)
         {
             result.setSuccess(false);
             result.setMessage(String.format("银行订单号%s重复，新增失败！",teslaBankRequest.getBankRequestNo()));
             return  result;
         }
        if(teslaBankRequest.getBankRequestState().equals("1"))
        {
            teslaBankRequest.setSendTime(new Date());
        }
         teslaBankRequest.setCreatedDate(new Date());
         teslaBankRequest.setBankCode(user.getBankCode());
         teslaBankRequest.setRequestNo(generateId());
         int ret = teslaBankRequestMapper.insertSelective(teslaBankRequest);
        if(ret >0)
        {
            result.setSuccess(true);
            result.setMessage("OK");
        }else{
            result.setSuccess(false);
            result.setMessage("fail");
        }

        return result;
    }

    public List<TeslaBankRequest> queryBankRequest(TeslaBankRequest request) {
        List<TeslaBankRequest> requests =  teslaBankRequestMapper.queryBankRequestList(request);
        return requests;
    }

    public Long queryBankRequestCont(TeslaBankRequest request) {
        Long count =  teslaBankRequestMapper.queryBankRequestCount(request);
        return count;
    }

    public List<TeslaBankRequest> queryByBankRequestNo(String bankRequestNo) {
        TeslaBankRequest request = new TeslaBankRequest();
        request.setBankRequestNo(bankRequestNo);
        List<TeslaBankRequest> requests =   queryBankRequest(request);
        return requests;
    }

    public List<TeslaBankRequest> queryByRequestId(Long requestId) {
        TeslaBankRequest request = new TeslaBankRequest();
        request.setId(requestId);
        List<TeslaBankRequest> requests =   queryBankRequest(request);
        return requests;
    }

    public CommonResult<String> updateRequest(TeslaBankRequest teslaBankRequest) {
        CommonResult<String> result = new CommonResult<String>();
        if(teslaBankRequest.getBankRequestState().equals("1"))
        {
            teslaBankRequest.setSendTime(new Date());
        }
        int ret = teslaBankRequestMapper.updateByPrimaryKeySelective(teslaBankRequest);
        if(ret >0)
        {
            result.setSuccess(true);
            result.setMessage("OK");
        }else{
            result.setSuccess(false);
            result.setMessage("fail");
        }

        return result;
    }




    public String generateId()
    {
        return DateFormatUtils.format(new Date() , "yyyyMMddHHmmssSSS");
    }

    public String uploadFile(MultipartFile uploadObject) {
        String uploadpath = CommonUtil.getPropertiesByFile("des","uploadpath");
        String project = CommonUtil.getPropertiesByFile("des","projectname");
        File updir = new File (  uploadpath+"/"+project);
        if(!updir.exists()){
            updir.mkdir();
        }
        Map<String,Object> result = new HashMap<String, Object>();
        String orgiginalFileName ="";
        try {
            orgiginalFileName = uploadObject.getOriginalFilename();
            FileUtils.copyInputStreamToFile(uploadObject.getInputStream() ,new File(updir ,orgiginalFileName ) );

        } catch (IOException e) {
            e.printStackTrace();
        }
        result.put("fileName",orgiginalFileName);
        result.put("success",true);
        return JSON.toJSONString(result);
    }

    public String deleteFile(String fileName) {
        Map<String,Object> result = new HashMap<String, Object>();
        String uploadpath = CommonUtil.getPropertiesByFile("des","uploadpath");
        String project = CommonUtil.getPropertiesByFile("des","projectname");
        File desFile = new File (  uploadpath+"/"+project+"/"+fileName);
        if(desFile.exists())
        {
            if(desFile.delete())
            {
                result.put("fileName",fileName);
                result.put("success",true);
                return  JSON.toJSONString(result);
            }
        }
        result.put("fileName",fileName);
        result.put("success",false);
        return JSON.toJSONString(result);
    }

    public Map<String,Object> deleteRequest(String id) {
        Map<String,Object> map = new HashMap<String, Object>();
        if(StringUtils.isNotBlank(id)){
            String[] idseg = id.split(";");
            for(String item :idseg){
                if(StringUtils.isNotBlank(item)){
                    item = item.trim();
                    int key = Integer.parseInt(item);
                    teslaBankRequestMapper.deleteByPrimaryKey(key);
                }
            }
        }
        map.put("success",true);
        return map;
    }

    public ResponseEntity<byte[]> downloadFile(String fileName) {
        String uploadpath = CommonUtil.getPropertiesByFile("des","uploadpath");
        String project = CommonUtil.getPropertiesByFile("des","projectname");
        File desFile = new File (  uploadpath+"/"+project+"/"+fileName);
        byte[] datas = new byte[1024];
        if(desFile.exists())
        {
            try {
                datas =  IOUtils.toByteArray (new FileInputStream(desFile));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        try {
            headers.setContentDispositionFormData("attachment", new String(fileName.getBytes("utf-8"), "ISO8859-1"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        HttpStatus statusCode = HttpStatus.OK;
        ResponseEntity<byte[]> entity = new ResponseEntity<byte[]>(datas, headers, statusCode);
        return entity;
    }

    public String exportRequest(String selectId , String bankRequestType) {
        StringBuffer sb = new StringBuffer();
        String title = "";
        if(bankRequestType.equals("0")){
            title = "序列号,银行订单号,查询类型,紧急状态,交易时间,交易金额,姓名,身份证号,预留手机号,是否拦截,查询状态,银行备注";
        }else{
            title ="序列号,银行卡号,查询类型,紧急状态,交易时间,交易金额,姓名,身份证号,预留手机号,是否拦截,查询状态,银行备注";
        }
        sb.append(title+"\n");
        String items = queryRequestToExport(selectId);
        sb.append(items);
        return sb.toString();
    }


    public String queryRequestToExport(String selectId){

        TeslaBankRequest query = new TeslaBankRequest();
        query.setIdRange(selectId);
        List<TeslaBankRequest> teslaBankRequests = teslaBankRequestMapper.queryBankRequestList(query);
        StringBuffer sb = new StringBuffer();
        for(TeslaBankRequest request :teslaBankRequests){
            StringBuffer itemSb = new StringBuffer();
            itemSb.append(request.getRequestNo()+"\t,");
            itemSb.append(request.getBankRequestNo()+"\t,");
            if(request.getBankRequestType().equals("0")){
                itemSb.append("查询,");
            }else if(request.getBankRequestType().equals("1")){
                itemSb.append("拒付,");
            }
            if(request.getEmergencyState().equals("0")){
                itemSb.append("普通,");
            }else if(request.getEmergencyState().equals("1")){
                itemSb.append("紧急,");
            }
            itemSb.append( DateFormatUtils.format(request.getTradeDate() , "yyyy-MM-dd")+",");
            itemSb.append(request.getTradeMoney()+",");
            itemSb.append(request.getRealName()+",");
            itemSb.append(request.getCertno()+"\t,");
            itemSb.append(request.getTelephone()+"\t,");
            if(request.getInterceptState().equals("1")){
                itemSb.append("是,");
            }else{
                itemSb.append("否,");
            }

            if(request.getBankRequestState().equals("0")){
                itemSb.append("未发送,");
            }else if(request.getBankRequestState().equals("1")){
                itemSb.append("未回复,");
            }else{
                itemSb.append("已回复,");
            }
            itemSb.append(request.getRemark()+",");
            itemSb.append("\n");
            sb.append(itemSb.toString());
        }
        return sb.toString();
    }

    public String exportReply(TeslaBankRequest request) {
        StringBuffer sb = new StringBuffer();
        String title = "";
        if(request.getBankRequestType().equals("0")){
            title = "序列号,银行名称,查询类型,紧急状态,银行订单号,交易时间,交易金额,姓名,身份证号,预留手机号,是否拦截,查询状态,银行备注";
        }else{
            title ="序列号,银行名称,查询类型,紧急状态,银行卡号,交易时间,交易金额,姓名,身份证号,预留手机号,是否拦截,查询状态,银行备注";
        }
        sb.append(title+"\n");
        String items = queryReplyToExport(request);
        sb.append(items);
        return sb.toString();

    }

    private String queryReplyToExport(TeslaBankRequest query) {
        List<TeslaBankRequest> teslaBankRequests = teslaBankRequestMapper.queryBankRequestList(query);
        StringBuffer sb = new StringBuffer();
        for(TeslaBankRequest request :teslaBankRequests){
            StringBuffer itemSb = new StringBuffer();
            itemSb.append(request.getRequestNo()+"\t,");
            if(CodeInfoUtils.bankCodeMap.containsKey( request.getBankCode())){
                itemSb.append(CodeInfoUtils.bankCodeMap.get(request.getBankCode())+",");
            }else{
                itemSb.append(request.getBankCode() +",");
            }
            if(request.getBankRequestType().equals("0")){
                itemSb.append("查询,");
            }else if(request.getBankRequestType().equals("1")){
                itemSb.append("拒付,");
            }
            if(request.getEmergencyState().equals("0")){
                itemSb.append("普通,");
            }else if(request.getEmergencyState().equals("1")){
                itemSb.append("紧急,");
            }
            itemSb.append(request.getBankRequestNo()+"\t,");
            itemSb.append( DateFormatUtils.format(request.getTradeDate() , "yyyy-MM-dd")+",");

            itemSb.append(request.getTradeMoney()+",");
            itemSb.append(request.getRealName()+",");
            itemSb.append(request.getCertno()+"\t,");
            itemSb.append(request.getTelephone()+"\t,");
            if(request.getInterceptState().equals("1")){
                itemSb.append("是,");
            }else{
                itemSb.append("否,");
            }

            if(request.getBankRequestState().equals("0")){
                itemSb.append("未发送,");
            }else if(request.getBankRequestState().equals("1")){
                itemSb.append("未回复,");
            }else{
                itemSb.append("已回复,");
            }
            itemSb.append(request.getRemark()+",");
            itemSb.append("\n");
            sb.append(itemSb.toString());
        }
        return sb.toString();
    }

    public void batchBankOrderRequest(InputStream inputStream, String orgiginalFileName, String bankRequestType)  {
        Map<Integer ,String> config = new HashMap<Integer, String>();
        config.put(0 , "requestNo");
        config.put(1 , "bankRequestNo");
        config.put(2 , "requestType");
        config.put(3 , "emergencyState");
        config.put(4 , "tradeDate");
        config.put(5 , "tradeMoney");
        config.put(6 , "realName");
        config.put(7 , "certno");
        config.put(8 , "telephone");
        config.put(9 , "interceptState");
        config.put(10 , "bankRequestState");
        config.put(11 , "remark");
        List<TeslaBankRequest> requestList = new ArrayList<TeslaBankRequest>();
        try {
            List<Map<String,String>> maps  = FileExcelUtil.readExcel(inputStream,orgiginalFileName,1,config);
            for(Map<String,String> map :maps){
                TeslaBankRequest request = new TeslaBankRequest();
                request.setBankRequestType(bankRequestType);
                request.setRequestNo(map.get("requestNo"));
                request.setBankRequestNo(map.get("bankRequestNo"));
                String requestType = map.get("bankRequestType");
                if(requestType.equals("查询")){
                    request.setRequestType("0");
                }else{
                    request.setRequestType("1");
                }
                String emergencyState = map.get("emergencyState");
                if(emergencyState.equals("普通")){
                    request.setEmergencyState("0");
                }else{
                    request.setEmergencyState("1");
                }
                String tradeDateStr =  null!=map.get("tradeDate") ? map.get("tradeDate"):null;
                if(null!=tradeDateStr){
                    Date tradeDate = DateUtils.parseDate(tradeDateStr , new String[]{"yyyy-MM-dd"});
                    request.setTradeDate(tradeDate);
                }
                BigDecimal tradeMoney = new BigDecimal(map.get("tradeMoney"));
                request.setTradeMoney( tradeMoney);
                request.setRealName(map.get("realName"));
                request.setCertno(map.get("certno"));
                request.setTelephone(map.get("telephone"));
                String interceptState = map.get("interceptState");
                if(interceptState.equals("拦截")){
                    request.setInterceptState("1");
                }else{
                    request.setInterceptState("0");
                }
                String bankRequestState = map.get("bankRequestState");
                if(bankRequestState.equals("未发送")){
                    request.setBankRequestState("0");
                }else if(bankRequestState.equals("未回复")){
                    request.setBankRequestState("1");
                }else{
                    request.setBankRequestState("2");
                }
                request.setRemark(map.get("remark"));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
